package com.cheng.spider.analyze;

import com.cheng.spider.constant.MimeType;
import com.cheng.spider.exception.UnsupportedMimeException;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractMimeTypeMatcher implements MimeTypeMatcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMimeTypeMatcher.class);

    @Override
    public MimeType matches(HttpResponse response) {
        String mimeString = getMimeType(response);
        String[] candicateType = mimeString.split(";");//text/html;charset=utf-8
        String[] mimes = candicateType[0].split("/");
        LOGGER.info("响应MIME类型：" + mimeString);
        MimeType mimeType = matches(mimes[0], mimes[1]);
        if (mimeType.isText()) {
            mimeType.setCharset(candicateType[1].split("=")[1]);
        }
        return mimeType;
    }

    private MimeType matches(String mainType, String subType) {
        MimeType mimeType = MimeType.UN_MATCHES;
        for (MimeType value : MimeType.values()) {
            if (value.matches(mainType, subType)) {
                mimeType = value;
                break;
            }
        }
        if (MimeType.UN_MATCHES.equals(mimeType)) {
            throw new UnsupportedMimeException("不支持的MIME类型：" + mainType + "/" + subType);
        }
        return mimeType;
    }

    protected abstract String getMimeType(HttpResponse response);
}
